package com.yh.csx.crm.core.util;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Huang Zhaoping
 * @date 2019/4/22
 */
public class ExcelUtils {

    public static <T extends BaseRowModel> List<T> readObjectList(InputStream input, int sheetNo, int headLineNo, Class<T> type) {
        ModelExcelListener<T> listener = new ModelExcelListener<>();
        ExcelReader reader = new ExcelReader(new BufferedInputStream(input), null, listener, true);
        reader.read(new Sheet(sheetNo, headLineNo, type));
        return listener.getDataList();
    }

    private static class ModelExcelListener<T> extends AnalysisEventListener<T> {

        private List<T> dataList = new ArrayList<>();

        @Override
        public void invoke(T object, AnalysisContext context) {
            dataList.add(object);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
        }

        public List<T> getDataList() {
            return dataList;
        }
    }

}
